examineNextCandle <- function(TS, pattern) {
  if (!is.OC(TS)) {
    stop("TS Price series must contain Open and Close")
  }
  if (dim(pattern)[2] != 1) {
    stop ("pattern must be a one- column XTS object")
  }
  LAGTS <- LagOC(TS, k=1)
  LAGpat <- Lag(pattern, k=1)
  HigherOpen  <- LAGpat & Op(TS) > Cl(LAGTS)
  LowerOpen   <- LAGpat & Op(TS) < Cl(LAGTS)
  WhiteCandle <- LAGpat & Op(TS) < Cl(TS)
  BlackCandle <- LAGpat & Op(TS) > Cl(TS)
  HigherClose <- LAGpat & Cl(TS) > Cl(LAGTS)
  LowerClose  <- LAGpat & Cl(TS) < Cl(LAGTS)
  
  result <- reclass(cbind(LAGpat, HigherOpen, LowerOpen, WhiteCandle, BlackCandle, HigherClose, LowerClose), TS)
  colnames(result) <- c("Obs", "HigherOpen", "LowerOpen", "WhiteCandle", "BlackCandle", "HigherClose", "LowerClose")
  return(result[2:dim(result)[1],])
}

getAllNextCandleGroupOverview <- function(OOS=FALSE) {
  SUFFIX<-""
  if (OOS==TRUE) {
    SUFFIX<-"_OOS"
  }
  nextCandleGroupOverview(paste("INDEX_MAJORS", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
  nextCandleGroupOverview(paste("DJI_STOCKS", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
  nextCandleGroupOverview(paste("SMALL_CAPS", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
  nextCandleGroupOverview(paste("METALS", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
  nextCandleGroupOverview(paste("AGRICULTURE", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
  nextCandleGroupOverview(paste("FOREX_MAJORS", SUFFIX, sep=""), latex=TRUE, trendfilter="Donchian Channel")
}

nextCandleGroupOverview <- function(groupcode, Pversion=0, calc="pct", latex=FALSE, trendfilter="") {
  if('package:xtable' %in% search() || require('xtable',quietly=TRUE)) {}
  calcPct <- function() {
    for (i in 1:dim(retDF)[1]) {
      for (j in 2:(dim(retDF)[2]-1)) {
        retDF[i,j] <<- retDF[i,j]*100 / retDF[i,8]
      }
    }
  }
  groupinfo <- getDBGroup(groupcode)  # retrieve table with stock_id, code, from, to
  patternlist <- getCSPGroupPattern(groupcode, Pversion=Pversion)
  patternlistnames <- names(patternlist)
  
  # form skeleton of return-dataframe
  retDF <- as.data.frame(matrix(0, nrow=length(colnames(patternlist[[1]])),ncol=8))
  colnames(retDF) <- c("pattern", "HigherOpen", "LowerOpen", "HigherClose", "LowerClose", "WhiteCandle", "BlackCandle", "Obs")
  retDF[,1] <- colnames(patternlist[[1]])
  
  # loop throught every group item
  for (i in 1:length(patternlist)) {
    symname <- paste(patternlistnames[i], ".vadb", sep="")
    fromtodates <- getGroupMember(groupinfo, patternlistnames[i])
    subsetstring = paste(fromtodates[1], "/", sep="") # ensure that TS and FILTER have same indexes
    CSPatterns <- colnames(patternlist[[i]])
    # loop through every pattern
    for (j in 1:length(CSPatterns)) {
      thisSum <- colSums(examineNextCandle(get(symname)[subsetstring], patternlist[[i]][,CSPatterns[j]]))
      retDF[j,"HigherOpen"] <- retDF[j,"HigherOpen"] + thisSum["HigherOpen"]
      retDF[j,"LowerOpen"] <- retDF[j,"LowerOpen"] + thisSum["LowerOpen"]
      retDF[j,"HigherClose"] <- retDF[j,"HigherClose"] + thisSum["HigherClose"]
      retDF[j,"LowerClose"] <- retDF[j,"LowerClose"] + thisSum["LowerClose"]
      retDF[j,"WhiteCandle"] <- retDF[j,"WhiteCandle"] + thisSum["WhiteCandle"]
      retDF[j,"BlackCandle"] <- retDF[j,"BlackCandle"] + thisSum["BlackCandle"]
      retDF[j,"Obs"] <- retDF[j,"Obs"] + thisSum["Obs"]      
    }
  }
  if (calc=="pct") {
    calcPct()
  } else if (calc!="total") {
    stop ("invalid parameter calc given. use 'pct' or 'total'")
  }
  
  if (latex==TRUE) {
    title <- sprintf("Lage und Farbe der Folgekerze nach Auftreten von Candlestick Muster. 
    Datensatz: %s; Trendfilterung: %s", groupcode, trendfilter)
    label <- sprintf("tab:nextCandle:%s:%s", groupcode, trendfilter)
    xt <- xtable(retDF,
                 caption=title,
                 label=label,
                 align="r|r|cc|cc|cc|r|",
                 display=c("s", "s", "f","f", "f","f", "f","f", "d"))
    print(xt, include.rownames=FALSE)
  } else {
    return(retDF)
  }
}


compareCSPgrNextCandle <- function(groupcode, meanlimit=.5, pctlimit=12, Pversion=0) {
  tbl <- tableRetMeanSd(getCSPGroupReturn(groupcode, Pversion=Pversion,n=20) ,latex=FALSE)
  tbl <- tbl[with(tbl, order(pattern)),]
  # tbl[,1] contains pattern name
  # tbl[,6] contains pattern mean after 10 days
  nextC <- nextCandleGroupOverview(groupcode, latex=FALSE)
  nextC <- nextC[with(nextC, order(pattern)), ]
  # nextC[,1] contains pattern name, but not neccessarily in same order
  
  retDF <- as.data.frame(matrix(0,nrow=dim(nextC)[1],ncol=4))
  colnames(retDF) <- c("pattern", "open", "close", "color")
  for (i in 1:dim(tbl)[1]) {
    if (tbl[i,1] != nextC[i,1]) {
      stop ("pattern indexes don't match")
    }
    retDF[i,1] <- tbl[i,1]
    if (tbl[i,2] > meanlimit | tbl[i,4] > meanlimit | tbl[i,6] > meanlimit | tbl[i,8] > meanlimit) {
      if ((nextC[i,3] - nextC[i,2]) > pctlimit) {
        retDF[i,2] = 1
      }
      if ((nextC[i,5] - nextC[i,4]) > pctlimit) {
        retDF[i,3] = 1
      }
      if ((nextC[i,7] - nextC[i,6]) > pctlimit) {
        retDF[i,4] = 1
      }
    }
    if (tbl[i,2]*(-1) > meanlimit | tbl[i,4]*(-1) > meanlimit | tbl[i,6]*(-1) > meanlimit | tbl[i,8]*(-1) > meanlimit) {
      if ((nextC[i,2] - nextC[i,3]) > pctlimit) {
        retDF[i,2] = retDF[i,2] -2
      }
      if ((nextC[i,4] - nextC[i,5]) > pctlimit) {
        retDF[i,3] = retDF[i,3] -2
      }
      if ((nextC[i,6] - nextC[i,7]) > pctlimit) {
        retDF[i,4] = retDF[i,4] -2
      }      
    }
  }
  return(retDF)
}